<template>
  <div class="app-container">
      <div style="float:left;width:300px;">
        <div style="border:1px solid #eee;height:calc(100vh - 150px);padding:20px 10px;overflow: auto">
          <div style="text-align: right">
            <el-button
              size="mini"
              type="primary"
              class="btn-add"
              v-if="isCanAdd"
              @click="changeRoles('add',null,null)">
              新增角色
            </el-button>
          </div>
          <div class="management-list" v-loading="listLoading">
              <div class="list-item" :class="{'active':index == activeIndex}"  v-for="(item,index) in list">
                <span v-if="isCanEdit"  @click="changeRoles('edit',item,index)">{{item.roleName}}</span>
                <span v-else>{{item.roleName}}</span>
                <div style="float:right;width:100px;text-align: right">
                  <el-button
                    v-if="isCanEdit"
                    type="text"
                    size="mini"
                    @click="changeRoles('edit',item,index)">
                    修改
                  </el-button>
                  <el-button
                    v-if="isCanDel"
                    type="text"
                    size="mini"
                    @click="delRoleItem(item)">
                    删除
                  </el-button>
                </div>

              </div>
          </div>
        </div>
      </div>
      <div style="float:left;width:calc(100% - 350px);margin-left:20px">
        <div style="border:1px solid #eee;height:calc(100vh - 150px);padding:20px;position: relative" class="manageForm-div" v-if="show">
          <el-form :model="manageForm" size="mini" label-width="100px" :rules="rules" ref="manageForm" style="height:100%;">
            <el-form-item label="角色名称：" prop="roleName">
              <el-input v-model="manageForm.roleName" placeholder="角色名称" style="width:150px" :disabled="!isCanEdit"></el-input>
            </el-form-item>
            <el-tabs style="height:calc(100% - 50px);" v-model="activeName">
              <el-tab-pane label="菜单权限" name="first" style="height:calc(100% - 100px);overflow: auto">
                <div>
                  <el-checkbox-group v-model="manageForm.permissions">
                      <div class="permissions-item" v-for="(item,index) in permissionsList">
                        <div class="permissions-title">
                          <el-checkbox :label="item.code" @change="changePage(item,index)" :disabled="item.code == 'index'">{{item.name}}</el-checkbox>
                        </div>
                        <div class="permissions-list">
                            <span v-for="cItem in item.permissions" class="permissions-span">
                                <el-checkbox :label="cItem.code" @change="changeBtn(cItem)">{{cItem.name}}</el-checkbox>
                            </span>
                        </div>
                      </div>
                  </el-checkbox-group>
                </div>
              </el-tab-pane>
            </el-tabs>
          </el-form>
          <div style="width:100%;position: absolute;bottom:20px;text-align: center">
            <el-button type="primary" @click="handleConfirm" size="small" :loading="btnLoading">保存角色</el-button>
          </div>
        </div>
      </div>

  </div>
</template>
<script>
  import {getRoleList,RoleInfo,getPermissions,delRoles} from '@/api/management'
  import store from '@/store'
  const defaultListQuery = {
    pageNum: 1,
    pageSize: 1000,
  };
  const defaultManageForm = {
    roleName:null,
    permissions:['index']
  };
  export default {
    name: "managementSetting",
    data(){
      return{
        listQuery: Object.assign({}, defaultListQuery),
        manageForm:JSON.parse(JSON.stringify(defaultManageForm)),
        rules: {
          roleName: [
            {required: true, message: '请输入角色名称', trigger: 'blur'},
          ],
        },
        list:[],
        listLoading: false,
        activeIndex:null,
        permissionsList:[],
        activeName:'first',
        show:false,
        btnLoading:false,
        roles:store.getters.roles ? store.getters.roles : [],
      }
    },
    created() {
      this.getPermissionsList();
      this.getList();
    },
    computed: {
        isCanAdd() {
            if(this.roles.indexOf("addRole") != -1){
                return true
            }else{
                return false
            }
        },
        isCanEdit(){
            if(this.roles.indexOf("editRole") != -1){
                return true
            }else{
                return false
            }
        },
        isCanDel(){
            if(this.roles.indexOf("deleteRole") != -1){
                return true
            }else{
                return false
            }
        },
    },
    filters: {

    },
    methods:{
        //切换页面权限
        changePage(item,index){
            let code = item.code;
            if(this.manageForm.permissions.indexOf(code) == -1){
                item.permissions.forEach((el)=>{
                    let i = this.manageForm.permissions.findIndex((ee)=>{
                        return ee == el.code;
                    });
                    if(i != -1){
                        this.manageForm.permissions.splice(i,1);
                    }
                });
            }
        },

        //切换页面功能
        changeBtn(item){
            let code = item.code;
            let parent_id = item.parent_id;
            if(this.manageForm.permissions.indexOf(code) != -1){ // 选择页面功能
                  let curPage = this.permissionsList.find((el)=>{ //找出当前功能属于那个页面
                        return el.id == parent_id;
                  });
                   if(this.manageForm.permissions.indexOf(curPage.code) == -1){ //如果当前功能属于的页面，没有被选中则强制选上
                        this.manageForm.permissions.push(curPage.code)
                   }
            }
        },


        //获取权限列表
        getPermissionsList(){
            getPermissions().then((res)=>{
                this.permissionsList = res;
            })
        },

      /**
       *获取列表
       **/
      getList() {
        this.listLoading = true;
        let listQuery = JSON.parse(JSON.stringify(this.listQuery));
        getRoleList(listQuery).then(response => {
          this.listLoading = false;
          this.list = response.list;
        });
      },

      //显示角色详情
      changeRoles(type,item,index){
        this.show = true;
        if (type == 'add'){
          this.manageForm = JSON.parse(JSON.stringify(defaultManageForm));
        }else{
          this.activeIndex = index;
          this.manageForm = JSON.parse(JSON.stringify(item));
          if(this.manageForm.permissions.indexOf("index") == -1){
              this.manageForm.permissions.push("index")
          }
        }
        setTimeout(()=>{
            this.$refs.manageForm.clearValidate();
        },0)

      },

      //新增编辑角色
      handleConfirm(){
        this.$refs.manageForm.validate((valid) => {
          if (valid) {
              this.btnLoading = true;
              let data = {};
              data.roleName = this.manageForm.roleName;
              data.permissions = this.manageForm.permissions;
              if (this.manageForm.roleId) { // 编辑
                  data.roleId = this.manageForm.roleId;
              }
              RoleInfo(data).then(response => {
                  this.btnLoading = false;
                  this.$message({
                      message: '提交成功',
                      type: 'success',
                      duration: 1000
                  });
                  this.getList();
                if (!this.manageForm.roleId) { //新增
                  this.manageForm = JSON.parse(JSON.stringify(defaultManageForm));
                }
              }).catch(()=>{
                  this.btnLoading = false;
              })
          }
        });
      },

      //删除角色
      delRoleItem(item){
          this.$confirm('确定删除角色?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
          }).then(() => {
              delRoles({roleId:item.roleId,rf:true}).then(()=>{
                  this.getList();
                  this.show = false;
                  this.activeIndex = null;
                  this.$message({
                      type: 'success',
                      message: '删除成功!'
                  });
              });

          }).catch(() => {
              this.$message({
                  type: 'info',
                  message: '已取消删除'
              });
          });
      },

    }

  }
</script>

<style lang="scss">
  .management-list{
    margin-top:20px;
    .list-item{
      font-size:12px;
      line-height: 30px;
      cursor: pointer;
      padding:0 16px;
      overflow: hidden;
    }
    .list-item.active{
      background: #ebf2fd;
    }
    .list-item:hover{
      background: #F5F7FA;
    }
    .list-item.active:hover{
      background: #e7f1ff;
    }
  }
  .manageForm-div{
    .el-tabs__content{
      height:100%;
    }
    .permissions-item{
      margin-top:20px;
      .permissions-title{
        line-height: 30px;
        .el-checkbox__label{
          font-size: 14px;
          font-weight: bold;
        }
      }
      .permissions-list{
        font-size: 12px;
        .permissions-span{
          display: inline-block;
          margin-right:20px;
            margin-bottom:20px;
        }
      }
    }


  }


</style>
